<template>
    <statusBar></statusBar>
    <!-- <view class="loginTypeChangeButton" v-if="isLogin" @click="changeLoginType">
        {{ loginType !== 1 ? '密码登录' : '验证码登录' }}
    </view> -->
    <view class="loginTypeChangeButton"></view>

    <view class="title">{{ isLogin ? '登录' : '注册' }}悦居云服</view>

    <view class="content" v-if="isLogin">
        <view class="inputs">
            <view class="item">
                <view class="itemTitle">手机号</view>
                <view class="inputBox">
                    <input type="tel" :maxlength="11" v-model.trim="loginInfomation.phone" placeholder="请输入手机号" />
                </view>
            </view>
            <view class="item" v-if="loginType === 1">
                <view class="itemTitle">密码</view>
                <view class="inputBox">
                    <input v-if="loginInfomation.passwordShow" :maxlength="12" v-model.trim="loginInfomation.password" placeholder="6-12位字母数字组合" />
                    <input v-else type="password" :maxlength="12" v-model.trim="loginInfomation.password" placeholder="6-12位字母数字组合" />
                    <view class="showIcon" @click="loginInfomation.passwordShow = !loginInfomation.passwordShow">
                        <image v-if="loginInfomation.passwordShow" src="/static/common/icon_show.png"></image>
                        <image v-else src="/static/common/icon_display.png"></image>
                    </view>
                </view>
            </view>

            <view class="item" v-else>
                <view class="itemTitle">验证码</view>
                <view class="inputBox">
                    <input type="text" :maxlength="6" v-model.trim="loginInfomation.verificationCode" placeholder="请输入验证码" />
                    <view class="getCode" :class="timer && 'gray'" @click="getVerificationCode">
                        {{ VerificationCodeButtonText }}
                    </view>
                </view>
            </view>
        </view>

        <view class="forgetPassword" v-if="loginType === 1" @click="goFindPSD">忘记密码</view>
        <view class="forgetPassword" v-else></view>

        <view class="submitButton" @click="login">登录</view>
        <view class="changeIsLogin" @click="chengePageType">还没有账号？去注册</view>
    </view>

    <view class="content" v-else>
        <view class="inputs">
            <view class="item">
                <view class="itemTitle">手机号</view>
                <view class="inputBox">
                    <input type="tel" :maxlength="11" v-model.trim="loginInfomation.phone" placeholder="请输入手机号" />
                </view>
            </view>

            <view class="item">
                <view class="itemTitle">验证码</view>
                <view class="inputBox">
                    <input type="text" :maxlength="6" v-model.trim="loginInfomation.verificationCode" placeholder="请输入验证码" />
                    <view class="getCode" :class="timer && 'gray'" @click="getVerificationCode">
                        {{ VerificationCodeButtonText }}
                    </view>
                </view>
            </view>

            <!-- <view class="item">
                <view class="itemTitle">验证码</view>
                <view class="inputBox">
                    <input type="text" :maxlength="4" v-model.trim="loginInfomation.verificationCode" placeholder="请输入验证码" />
                    <view class="verificationCode">
                        <jp-verification-literalness
                            ref="literalness"
                            :contentWidth="80"
                            :contentHeight="40"
                            @getCode="getPicCode"
                            :securityCode="PICcode"
                        ></jp-verification-literalness>
                    </view>
                </view>
            </view> -->

            <view class="item">
                <view class="itemTitle">密码</view>
                <view class="inputBox">
                    <input v-if="loginInfomation.passwordShow" :maxlength="12" v-model.trim="loginInfomation.password" placeholder="6-12位字母数字组合" />
                    <input v-else type="password" :maxlength="12" v-model.trim="loginInfomation.password" placeholder="6-12位字母数字组合" />
                    <view class="showIcon" @click="loginInfomation.passwordShow = !loginInfomation.passwordShow">
                        <image v-if="loginInfomation.passwordShow" src="/static/common/icon_show.png"></image>
                        <image v-else src="/static/common/icon_display.png"></image>
                    </view>
                </view>
            </view>

            <view class="item">
                <view class="itemTitle">选择身份</view>
                <view class="inputBox">
                    <uni-data-select v-model="loginInfomation.identity" :localdata="identityOptions" placeholder="请选择你的身份"></uni-data-select>
                </view>
            </view>
            <view class="item" v-if="loginInfomation.identity == '1' || loginInfomation.identity == '2'">
                <view class="itemTitle">邀请码</view>
                <view class="inputBox">
                    <input type="text" :maxlength="6" v-model.trim="loginInfomation.invitedCode" placeholder="请输入邀请码" />
                </view>
            </view>
        </view>

        <view class="submitButton" @click="register">注册</view>
        <view class="changeIsLogin" @click="chengePageType">有账号去登录</view>
    </view>

    <view class="pageBottom">
        <template v-if="otherLoginType.length != 0">
            <view class="lineBox">
                <view class="line"></view>
                <view class="text">or</view>
                <view class="line"></view>
            </view>

            <view class="otherLogin">
                <view class="item" v-for="item in otherLoginType" :key="item.loginType">
                    <image :src="item.imgUrl" mode="widthFix"></image>
                </view>
            </view>
        </template>
        <view class="agreement" @click="checkAgreement">
            <view class="checkBox">
                <image v-if="isCheckedAgreement" src="/static/common/icon_checked.png"></image>
            </view>

            <view class="agreementText">
                同意
                <span @click.stop="goAgreement(1)">《悦居用户注册协议》</span>
                &
                <span @click.stop="goAgreement(2)">《隐私协议》</span>
            </view>
        </view>

        <view class="tips">如遇到登录问题请联系官方</view>
    </view>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { onLoad, onBackPress } from '@dcloudio/uni-app';
import { commonApis, userApis } from '@/utils/apis.ts';
import { encryptData, decryptData } from '@/utils/jsencrypt.js';
import { checkStrLengthIsNotZero, encryption } from '@/utils/utils';

import env from '@/config/env';

let outFlag = ref(false);
onBackPress((options) => {
    // 点击虚拟键或者侧滑的时候触发（不允许返回）
    if (options.from === 'backbutton') {
        if (!outFlag.value) {
            outFlag.value = true;
            uni.showToast({
                icon: 'none',
                title: '再按一次退出应用'
            });
        } else {
            outFlag.value = false;
            plus.runtime.quit();
        }

        return true;
    }
    // 否则则允许返回
    return false;
});

let isLogin = ref(true); //true登录  false注册
let loginType = ref(1); //1密码 2验证码
// 第三方登录方式 微信等
const otherLoginType = ref([
    // {
    //     loginType: 'vx',
    //     imgUrl: '/static/common/icon_wx_gray.png'
    // }
]);
// 注册选择身份
const identityOptions = ref([
    { value: '0', text: '悦居推客' },
    { value: '1', text: '悦居管家' },
    { value: '2', text: '运营中心' },
    { value: '4', text: '省级公司' }
]);

const getIdentity_type = async () => {
    let res = await userApis.getIdentityType();
    identityOptions.value = res.data;
    for (let s of identityOptions.value) {
        s.text = s.label;
    }
};

onLoad((e) => {
    if (e?.isLogin) {
        isLogin.value = true;
    }

    if (uni.getSystemInfoSync().platform === 'android') {
        let brand = uni.getSystemInfoSync().brand.toLowerCase();
        if (brand == 'huawei') {
            getIdentity_type();
        }
    }

    getPicCode();
});
const literalness = ref();
const PICcode = ref('');
const getPicCode = async () => {
    const res = await userApis.getValidateCode({
        randomStr: Date.now()
    });
    PICcode.value = res.data.code;
};

let loginInfomation = reactive({
    phone: '',
    password: '',
    verificationCode: '',
    passwordShow: false,
    identity: '',
    invitedCode: ''
});

// 获取验证码
const VerificationCodeTime = ref(60);
const isCountingDown = ref(false);
const VerificationCodeButtonText = ref('获取验证码');
const timer = ref(null);
const getVerificationCode = async () => {
    if (timer.value) return;
    userApis
        .getVerificationCode({
            phone: loginInfomation.phone,
            type: isLogin.value ? '1' : '2'
        })
        .then((res) => {
            isCountingDown.value = true;
            VerificationCodeButtonText.value = `${--VerificationCodeTime.value}秒后重新获取`;
            timer.value = setInterval(() => {
                VerificationCodeTime.value--;
                if (VerificationCodeTime.value <= 0) {
                    clearInterval(timer.value);
                    VerificationCodeTime.value = 60;
                    timer.value = null;
                    isCountingDown.value = false;
                    VerificationCodeButtonText.value = '获取验证码';
                } else {
                    VerificationCodeButtonText.value = `${VerificationCodeTime.value}秒后重新获取`;
                }
            }, 1000);
        });
};

const loginMethods = async () => {
    const res = await userApis.getValidateCode({
        randomStr: Date.now()
    });

    const userInfo = {
        username: loginInfomation.phone,
        password: loginInfomation.password,
        code: res.data.code,
        grant_type: 'password',
        scope: 'server',
        randomStr: res.data.randomStr
    };
    const user = encryption({
        data: userInfo,
        key: env.securityKey,
        param: ['password']
    });

    await userApis.loginByPassword(user).then((res) => {
        let result = res;
        let time = new Date().getTime();

        result.expires_in = time + result.expires_in * 1000;
        uni.setStorageSync('userLoginInfo', JSON.stringify(result));
        uni.setStorageSync('userId', res.user_id);
    });
};

// 登录
const login = async () => {
    if (!isCheckedAgreement.value) {
        uni.showModal({
            showCancel: false,
            title: '提示',
            content: '请查看并同意《悦居用户协议》&《隐私协议》后重试'
        });
        return;
    }

    if (loginType.value == 1) {
        await loginMethods();
    } else {
        await userApis
            .loginByVerificationCode({
                phone: loginInfomation.phone,
                code: loginInfomation.verificationCode,
                grant_type: 'sms_login'
            })
            .then((res) => {
                uni.setStorageSync('userLoginInfo', JSON.stringify(res));
                uni.setStorageSync('userId', res.user_id);
            });
    }

    uni.switchTab({
        url: '/pages/home/home'
    });
};
// 注册

const register = async () => {
    // uni.navigateTo({
    //     url: '/pages_user/setUserInfomation/setUserInfomation'
    // });

    // return;

    if (!isCheckedAgreement.value) {
        uni.showModal({
            showCancel: false,
            title: '提示',
            content: '请查看并同意《悦居用户协议》&《隐私协议》后重试'
        });
        return;
    }

    if (!checkStrLengthIsNotZero(loginInfomation.phone) || loginInfomation.phone.length != 11) {
        uni.showToast({
            icon: 'none',
            title: '请填写正确手机号'
        });
        return;
    }

    if (!checkStrLengthIsNotZero(loginInfomation.verificationCode)) {
        uni.showToast({
            icon: 'none',
            title: '请填写验证码'
        });
        return;
    }

    if (loginInfomation.password.length < 6) {
        uni.showToast({
            icon: 'none',
            title: '请填写6-12位密码'
        });
        return;
    }

    if (!checkStrLengthIsNotZero(loginInfomation.identity)) {
        uni.showToast({
            icon: 'none',
            title: '请选择身份'
        });
        return;
    }

    if (loginInfomation.identity !== '0' && loginInfomation.identity !== '4' && !checkStrLengthIsNotZero(loginInfomation.invitedCode)) {
        uni.showToast({
            icon: 'none',
            title: '邀请码不能为空'
        });
        return;
    }

    const params = {
        phone: loginInfomation.phone,
        code: loginInfomation.verificationCode,
        password: loginInfomation.password,
        identityType: loginInfomation.identity,
        inviteCode: loginInfomation.invitedCode,
        type: '1'
    };

    await commonApis.verifyPhone(params).then((res) => {
        if (res.data > 0) {
            uni.showToast({
                icon: 'none',
                title: '该手机已经注册过，请直接登录',
                mask: true
            });
            return;
        } else {
            if (loginInfomation.identity === '4') {
                commonApis.whitelistValidate(params.phone).then((res) => {
                    if (res.data) {
                        uni.navigateTo({
                            url: '/pages_user/setUserInfomation/setUserInfomation?infomation=' + JSON.stringify(params)
                        });
                    } else {
                        uni.showModal({
                            icon: 'none',
                            title: `尊敬的用户，若想加入悦居帮手成为省级公司，需先与市场部门负责人陶先生 13438272001（微信同号）进行联系沟通，了解相关事宜并开通权限。`,
                            confirmText: '复制电话',
                            success(res) {
                                if (res.confirm) {
                                    uni.setClipboardData({
                                        data: '13438272001',
                                        showToast: true
                                    });
                                }
                            }
                        });
                    }
                });
            } else if (loginInfomation.identity === '0') {
                commonApis.whitelistValidate2(params.phone).then((res) => {
                    if (res.data) {
                        uni.navigateTo({
                            url: '/pages_user/setUserInfomation/setUserInfomation?infomation=' + JSON.stringify(params)
                        });
                    } else {
                        uni.showModal({
                            icon: 'none',
                            title: `尊敬的用户，您还不是悦居帮手的会员，无法注册为悦居推客。请联系陶先生 13438272001（微信同号）`,
                            confirmText: '复制电话',
                            success(res) {
                                if (res.confirm) {
                                    uni.setClipboardData({
                                        data: '13438272001',
                                        showToast: true
                                    });
                                }
                            }
                        });
                    }
                });
            } else {
                uni.navigateTo({
                    url: '/pages_user/setUserInfomation/setUserInfomation?infomation=' + JSON.stringify(params)
                });
            }
        }
    });
};

// 跳转到协议
const goAgreement = (type) => {
    uni.navigateTo({
        url: '/pages_user/agreement/agreement?type=' + type
    });
};
// 跳转到忘记密码
const goFindPSD = () => {
    uni.navigateTo({
        url: '/pages_user/forgetPassword/forgetPassword'
    });
};

//修改登录/注册 状态
const chengePageType = () => {
    isLogin.value = !isLogin.value;
    if (timer.value) clearInterval(timer.value);
};
//修改密码/验证码 登录
const changeLoginType = () => {
    loginType.value = loginType.value === 1 ? 2 : 1;
    if (timer.value) clearInterval(timer.value);
};

// 同意协议
const isCheckedAgreement = ref(false);
const checkAgreement = () => {
    isCheckedAgreement.value = !isCheckedAgreement.value;
};
</script>

<style lang="scss" scoped>
.loginTypeChangeButton {
    padding: 28rpx 24rpx 0;
    font-weight: 400;
    font-size: 32rpx;
    color: #393939;
    text-align: right;
    height: 44px;
}

.title {
    padding: 8rpx 84rpx 50rpx;
    font-weight: 800;
    font-size: 48rpx;
    color: #111111;
}

.submitButton {
    width: 572rpx;
    height: 78rpx;
    background: #2c72ff;
    border-radius: 54rpx;
    font-size: 28rpx;
    color: #ffffff;
    line-height: 78rpx;
    text-align: center;
    margin: 40rpx auto 30rpx;
}

.changeIsLogin {
    font-size: 28rpx;
    color: #666666;
    text-align: center;
}

.content {
    padding: 0 84rpx 300rpx;

    .inputs {
        width: 100%;

        .item {
            width: 100%;
            height: 92rpx;
            margin-bottom: 20rpx;
            display: flex;
            align-items: center;
            border-bottom: 2rpx solid #f2f2f2;

            .itemTitle {
                width: 130rpx;
                font-size: 28rpx;
                line-height: 1;
                color: #393939;
                border-right: 2rpx solid #ccc;
            }

            .inputBox {
                flex: 1;
                padding-left: 12rpx;
                height: 92rpx;
                display: flex;
                align-items: center;

                input {
                    flex: 1;
                    height: 40rpx;
                    font-size: 28rpx;
                    color: #393939;
                    line-height: 40rpx;
                    padding: 0 20rpx;

                    &::placeholder {
                        color: #999999;
                    }
                }

                .getCode {
                    font-size: 28rpx;
                    color: #333333;
                    height: 40rpx;
                    padding: 0 10rpx;

                    &.gray {
                        color: #999;
                    }
                }

                .showIcon {
                    width: 40rpx;
                    height: 40rpx;
                    display: flex;
                    align-items: center;
                    justify-content: center;

                    image {
                        width: 32rpx;
                        height: 32rpx;
                    }
                }
            }
        }
    }

    .forgetPassword {
        font-size: 28rpx;
        line-height: 1;
        height: 28rpx;
        color: #393939;
        text-align: right;
    }
}

.pageBottom {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    background-color: #fff;
    padding: 10rpx 80rpx 30rpx;

    .lineBox {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 16rpx;

        .line {
            width: 260rpx;
            height: 2rpx;
            background-color: #e7e7e7;
        }

        .text {
            font-size: 28rpx;
            line-height: 1;
            color: #cdcdcd;
        }
    }

    .otherLogin {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 30rpx;
        flex-wrap: wrap;
        margin: 30rpx 0;

        .item {
            width: 72rpx;
            height: 72rpx;

            image {
                width: 100%;
                height: 100%;
            }
        }
    }

    .agreement {
        display: flex;
        gap: 16rpx;
        align-items: center;
        justify-content: center;
        margin-bottom: 28rpx;

        .checkBox {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 36rpx;
            height: 36rpx;
            border: 2rpx solid #2c72ff;
            border-radius: 50%;

            image {
                width: 20rpx;
                height: 16rpx;
            }
        }

        .agreementText {
            font-size: 24rpx;
            color: #a9a9a9;

            span {
                color: #2c72ff;
            }
        }
    }

    .tips {
        text-align: center;
        padding-left: -34rpx;
        font-size: 20rpx;
        color: #a9a9a9;
    }
}

::v-deep .uni-stat__select {
    .uni-select {
        border: none;
    }
}
</style>
